package com.lagou.edu.filter;

import com.lagou.edu.utils.ExpiryMap;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component  // 让容器扫描到，等同于注册了
public class IpFilter implements GlobalFilter, Ordered {

    /**
     * 时间
     */
    @Value("${iplimit.time}")
    private Integer limitTime;

    /**
     * 次数
     */
    @Value("${iplimit.count}")
    private Integer limitCount;

    //
    ExpiryMap<String, Integer> ips = new ExpiryMap<>();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 思路：获取客户端ip，判断是否在黑名单中，在的话就拒绝访问，不在的话就放行
        // 从上下文中取出request和response对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        // 从request对象中获取客户端ip
        String clientIp = request.getRemoteAddress().getHostString();
        Integer count = 0;
        if(ips.containsKey(clientIp)) {
            count = ips.get(clientIp);
            if(count > limitCount) {
                //拒绝请求
                String data = "403";
                DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
                response.setStatusCode(HttpStatus.FORBIDDEN);
                return response.writeWith(Mono.just(wrap));
            }
        }
        //更新当前IP的注册数
        ips.put(clientIp, count + 1, limitTime);
        // 合法请求，放行，执行后续的过滤器
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
